<template>
	<div class="cont p-b-70">
		<nav-bar :title="`${username ? '编辑' : '创建'}自定义跟群`" rightImg="https://h5.dhcc.wang/newprogram/wxRobot/nav_refresh_black.png" bgStyle="#ffffff"
            text-color="#333333" :rotate.sync="reload" @leftClick="back" rightText="刷新" @rightClick="refresh" />
		<div>
			<van-notice-bar wrapable :scrollable="false">
				<div class="sync-text font-12">如遇群信息或采集人显示不全，请先确保群已保存至通讯录中，然后点击右上方刷新按钮稍后重新尝试即可！</div>
				<!-- <div slot="right-icon" class="sync-btn m-l-5 font-12">刷新</div> -->
			</van-notice-bar>
			<!-- <div class="flex">
				<div></div>
				<div>刷新</div>
			</div> -->
		</div>
		<div class="m-l-10 m-r-10 m-t-10 content">
			<div class="content-title text-center font-16 m-b-5 text-bold">按步骤完成以下操作</div>
			<!-- 第一步 -->
			<div class="item">
				<div class="flex align-center item-title font-14 text-bold m-b-10"><span class="sort">1</span> 选择自选源头素材群({{sourceList.length || 0}}/{{ sourceTotal || 0 }})</div>
				<div class="item-grid">
					<div class="grid-box text-center font-11" v-for="(item, index) in sourceList" :key="item.user_name">
						<div class="flex align-center justify-center group-img">
							<img :src="item.small_head_img_url || 'https://h5.dhcc.wang/images/default_avatar.png'" alt="" class="img">
						</div>
						<div class="text-cut2">{{ item.nick_name }}</div>
						<van-icon name="clear" class="close" color="#666666" size="18" @click="delSource(item, index)"></van-icon>
					</div>
					<div class="grid-box text-center font-11" @click="handleSelect('source')" v-if="sourceList.length < sourceTotal">
						<div class="flex align-center justify-center group-img group-btn">
							<van-icon name="plus" />
						</div>
						<div>选择源头群</div>
					</div>
				</div>
			</div>
			<!-- 第二步 -->
			<div class="item">
				<div class="flex align-center item-title font-14 text-bold m-b-10"><span class="sort">2</span> 选择要采集的人({{userList.length || 0}}/{{ userTotal || 0 }})</div>
				<div class="item-grid">
					<div class="grid-box text-center font-11" v-for="(item, index) in userList" :key="item.user_name">
						<div class="flex align-center justify-center group-img">
							<img :src="item.small_head_img_url || 'https://h5.dhcc.wang/images/default_avatar.png'" alt="" class="img">
						</div>
						<div class="text-cut2">{{ item.nick_name }}</div>
						<van-icon name="clear" class="close" color="#666666" size="18" @click="delUser(index)"></van-icon>
					</div>
					<div class="grid-box text-center font-11" v-if="userList.length < userTotal" @click="handleSelect('user')">
						<div class="flex align-center justify-center group-img group-btn">
							<van-icon name="plus" />
						</div>
						<div>选择采集人</div>
					</div>
				</div>
			</div>
			<!-- 第三部 -->
			<div class="item">
				<div class="flex align-center item-title font-14 text-bold m-b-10"><span class="sort">3</span> 选择要发送到的发单群({{targetList.length || 0}}/{{ targetTotal || 0 }})</div>
				<div class="item-grid">
					<div class="grid-box text-center font-11" v-for="(item, index) in targetList" :key="item.user_name">
						<div class="flex align-center justify-center group-img">
							<img :src="item.small_head_img_url || 'https://h5.dhcc.wang/images/default_avatar.png'" alt="" class="img">
						</div>
						<div class="text-cut2">{{ item.nick_name }}</div>
						<van-icon name="clear" class="close" color="#666666" size="18" @click="delTarget(item, index)"></van-icon>
					</div>
					<div class="grid-box text-center font-11" v-if="targetList.length < targetTotal" @click="handleSelect('target')">
						<div class="flex align-center justify-center group-img group-btn">
							<van-icon name="plus" />
						</div>
						
						<div>选择发单群</div>
					</div>
				</div>
			</div>
		</div>
		<div class="footer van-hairline--top">
			<van-button  round block type="info"
				:color="config.mac_main_color"
				:disabled="!sourceList.length || !userList.length|| !targetList.length"
				@click="onConfirm">保存设置</van-button>
		</div>
		<van-popup v-model="showPopup" position="bottom" round safe-area-inset-bottom>
			<div class="popup-content">
				<div class="flex justify-between align-center  text-center m-b-5 p-lr-12">
					<div class="popup-title font-16 text-bold">
						选择{{ type == 'source' ? '源头群' : type == 'user' ? '要采集的人' : '发单群' }}
					</div>
					<div class="font-12 color-9" v-if="type === 'user'">请注意是用户微信昵称</div>
					<!-- <div class="font-12 color-9" v-if="type !== 'user'" @click="handleQuestion">为什么没有我的群？</div> -->
				</div>
				<div class="search">
					<van-search v-model="keyword" shape="round" background="#f5f5f5" show-action placeholder="输入关键词搜索" @search="handleSearch" @clear="handleSearch">
						<template #action>
							<div @click="handleSearch">搜索</div>
						</template>
					</van-search>
				</div>
				<div class="list p-t-10">
					<van-list v-model="loading" :immediate-check="false" :finished="finished" finished-text="没有更多了" @load="onLoad" v-if="list.length">
						<template v-if="type == 'source'">
							<van-radio-group v-model="sourceChecked">
								<div class="flex align-center list-item m-b-10 p-l-10 p-r-10" v-for="(item, index) in list" :key="item.user_name" @click="toggle(item)">
									<img :src="item.small_head_img_url || item.smallHeadImgUrl || 'https://h5.dhcc.wang/images/default_avatar.png'" class="item-img m-r-10 radius4"/>
									<div class="van-ellipsis">{{ item.nick_name || item.nickName }} <span v-if="item.member_count">({{ item.member_count }})</span> </div>
									<van-radio :name="item.user_name"  ref="checkboxes" icon-size="20px" class="check" :checked-color="config.mac_main_color"></van-radio>
								</div>
							</van-radio-group>
							
						</template>
						<template v-else>
							<div class="flex align-center list-item m-b-10 p-l-10 p-r-10" v-for="(item, index) in list" :key="item.user_name" @click="toggle(item)">
								<img :src="item.small_head_img_url || item.smallHeadImgUrl || 'https://h5.dhcc.wang/images/default_avatar.png'" class="item-img m-r-10 radius4"/>
								<div class="van-ellipsis">{{ item.nick_name || item.nickName }} <span v-if="item.member_count">({{ item.member_count }})</span> </div>
								<van-checkbox :value="item.checked"  ref="checkboxes" icon-size="20px" class="check" :checked-color="config.mac_main_color"></van-checkbox>
							</div>
						</template>
						<!-- <div class="flex align-center list-item m-b-10 p-l-10 p-r-10" v-for="(item, index) in list" :key="item.user_name" @click="toggle(item)">
							<img :src="item.small_head_img_url || item.smallHeadImgUrl || 'https://h5.dhcc.wang/images/default_avatar.png'" class="item-img m-r-10 radius4"/>
							<div class="van-ellipsis">{{ item.nick_name || item.nickName }} <span v-if="item.member_count">({{ item.member_count }})</span> </div>
							<van-checkbox :value="item.checked"  ref="checkboxes" icon-size="20px" class="check" :checked-color="config.mac_main_color"></van-checkbox>
						</div> -->
					</van-list>
					<noData v-else marginTop="50px" :text="`暂无数据`" />
				</div>
				<div class="m-l-10 m-r-10">
					<van-button  
						round 
						block 
						type="info" 
						:color="config.mac_main_color"
						@click="handleSure">确认</van-button>
				</div>
			</div>
		</van-popup>
	</div>
</template>
<script>
import { Button, Popup, List, Checkbox, Radio, RadioGroup, Search, Field, NoticeBar, Notify } from 'vant'
export default {
	components: {
		[Button.name]: Button,
		[Popup.name]: Popup,
		[List.name]: List,
		[Checkbox.name]: Checkbox,
		[Radio.name]: Radio,
		[Search.name]: Search,
		[Field.name]: Field,
		[NoticeBar.name]: NoticeBar,
		[RadioGroup.name]: RadioGroup,
		[Notify.name]: Notify
	},
	data () {
		return {
			loading: false,
			finished: false,
			username: null,
			title: '',
			reload: false,
			type: null,
			showPopup: false,
			imgUrl: '111',
			config: {},
			keyword: '',
			list: [],
			sourceTotal: 1,
			sourceList: [],
			targetTotal: 20,
			targetList: [],
			userTotal: 20,
			userList: [],
			currentPage: 1,
			originUserList: [],
			originData: null, // 原始数据（编辑时使用）
			checkList: [],
			sourceChecked: ''
		}
	},
	mounted () {
		let username = this.$route.query.username || ''
		this.username = decodeURIComponent(username) || ''
		this.config = this.$DB.get('robotCfg')
		this.$common.setHeader({
			str_link_color: '#ffffff',
			end_link_color: '#ffffff'
		})
		if (this.username && this.username !== '') {
			this.init()
		}
	},
	methods: {
		init () {
			this.getDetail()
		},
		// 智选跟群详情
		getDetail () {
			this.$api.autoFollowList({
				username: this.username
			}, true).then(res => {
				if (res.data.list && res.data.list.length) {
					let data = res.data.list[0]
					this.originData = JSON.parse(JSON.stringify(data))
					this.sourceList = [{...data.username_source}] || []
					this.userList = data.username_senders || []
					this.targetList = data.username_follows || []
				}
				console.log(res.data)
			})
		},
		// 同步联系人
		refresh () {
			if (this.reload) return
			this.reload = true
            this.$api.syncContact({}).then(async res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
				if (this.id) {
					this.init()
				}
            }).finally(() => {
				this.reload = false
            })
		},
		back () {
			this.$router.go(-1)
		},
		// 选择数据
		async handleSelect (type) {
			if (type == 'user' && !this.sourceList.length) { // 选择主持人 && 未选择源头群
				return this.$toast('请先完成第一步操作')
			}
			this.type = type
			this.list = []
			this.sourceChecked = ''
			this.keyword = ''
			if (type == 'user') {
				await this.getUserList(true)
			} else {
				await this.getGroupList(true)
			}
			this.showPopup = true
		},
		// 请求选择数据
		getGroupList (isFirst = false) {
			if (isFirst) {
				this.list = []
				this.currentPage = 1
				this.finished = false
			}
			this.$api.getListGroup({
				status: -1,
				group_type: 0,
				page: this.currentPage,
				pagesize: 10,
				nick_name: this.keyword
			}).then(res => {
				let {list = [], total = 0} = res.data
				// if (this.type == 'target') {
				// 	list = this.markChecked(list, this.targetList)
				// }
				this.list = [...this.list, ...list]
				this.currentPage++
                if (this.list.length >= total) {
                    this.finished = true
                }
			}).finally(() => {
				this.loading = false
			})
		},
		/**
		 * 保存
		 */
		onConfirm () {
			if (!this.sourceList.length) {
				return this.$toast('请选择自选源头素材群')
			}
			if (this.sourceList.length > this.sourceTotal) {
				return this.$toast('最多选择' + this.sourceTotal + '个素材群')
			}
			if (!this.userList.length) {
				return this.$toast('请选择采集人')
			}
			if (this.userList.length > this.userTotal) {
				return this.$toast('最多选择' + this.userTotal + '个采集人')
			}
			if (!this.targetList.length) {
				return this.$toast('请选择发单群')
			}
			if (this.targetList.length > this.targetTotal) {
				return this.$toast('最多选择' + this.targetTotal + '个发单群')
			}
			let hasSameId = this.checkSimilar(this.sourceList, this.targetList)
			if (hasSameId) {
				return this.$toast('请勿选择相同素材群与发单群')
			}
			let http = null
			const newData = {
				username_source: this.sourceList[0],
				username_senders: this.userList,
				username_follows: this.targetList
			}
			const jsonStr = {
				new_data: newData
			}
			if (this.username) { // 编辑
				jsonStr.old_data = this.originData
			}
			this.$api.autoFollowAddOrUpdate({
				json_str: JSON.stringify(jsonStr)
			}).then(res => {
				if (res.code != 1) {
                    return this.$toast(res.msg)
                }
				this.showNotify()
				// this.$toast('保存成功')
				// this.$router.go(-1)
			})
			
		},
		toggle (item) {
			let flag = item.checked || false
			this.$set(item, 'checked', !flag)
		},
		/**
		 * 移除源头群
		 * 1、先将源头群清除（编辑时，调接口清除）
		 * 2、清除主持人
		 * @param {点击的下标} index 
		 */
		delSource (item, index) {
			this.sourceList.splice(index, 1)
			this.userList = []
		},
		/**
		 * 移除主持人
		 * @param {当前操作的数据下标} index 
		 */
		delUser (index) {
			this.userList.splice(index, 1)
		},
		/**
		 * 移除跟单群
		 * 编辑时，需使用接口清除
		 * @param {*当前数据} item 
		 * @param {数据下标} index 
		 */
		delTarget (item, index) {
			this.targetList.splice(index, 1)
		},
		handleSearch () {
			if (this.type == 'user') {
				this.$toast.loading({
					message: '加载中...',
					duration: 0,
					forbidClick: true
				})
				let list = JSON.parse(JSON.stringify(this.originUserList))
				if (!this.keyword.trim()) { // 没有关键词
					this.list = this.originUserList
				} else {
					this.list = list.filter(item => item.nickName.includes(this.keyword))
				}
				setTimeout(() => {
					this.$toast.clear()
					this.finished = true
				}, 1000)
			} else {
				this.getGroupList(true)
			}
			
			// if (this.type == 'user'){
			// 	this.getUserList(true)
			// } else {
			// 	this.getGroupList(true)
			// }
		},
		filterList (list, keyword) {
			if (!this.keyword.trim()) { // 为空
				return this.list
			}
		},
		/**
		 * 保存选中数据
		 * 1、判断是否已存在，存在则不添加
		 * 2、判断是否超过上限，超过上限则提示
		 * 注：主持人与所选素材群关联
		 */
		handleSure () {
			const total =
				this.type === 'source'
				? this.sourceTotal
				: this.type === 'user'
				? this.userTotal
				: this.targetTotal;
			// 获取结果列表
			let result = this.type === 'source'
				? this.list.filter(item => item.user_name === this.sourceChecked)
				: this.list.filter(item => item.checked);

			// 统一映射字段
			const mapFields = ({
				user_name,
				userName,
				small_head_img_url,
				smallHeadImgUrl,
				nick_name,
				nickName,
				owner = ''
			}) => {
				return this.type === 'user'
					? {
						user_name: userName,
						small_head_img_url: smallHeadImgUrl,
						nick_name: nickName,
						owner
					}
					: {
						user_name,
						small_head_img_url,
						nick_name,
						owner
					};
			};
			// 映射字段
			result = result.map(mapFields);
			// if (this.type == 'source') {
			// 	result = this.list.filter(item => item.user_name == this.sourceChecked)

			// } else {
			// 	result = this.list
			// 	.filter(item => item.checked)
			// }

			// result = result.map(({ 
			// 	user_name, 
			// 	userName,
			// 	small_head_img_url,
			// 	smallHeadImgUrl, 
			// 	nick_name,
			// 	nickName, 
			// 	owner = '' }) => {
			// 		if (this.type == 'user') {
			// 			return {
			// 				user_name: userName,
			// 				small_head_img_url: smallHeadImgUrl,
			// 				nick_name: nickName,
			// 				owner
			// 			}
			// 		} else {
			// 			return {
			// 				user_name,
			// 				small_head_img_url,
			// 				nick_name,
			// 				owner
			// 			}
			// 		}
			// 	});

			if (!result.length) {
				return this.$toast('请选择数据')
			}
			if (result.length > total) {
				return this.$toast(`最多可选择${total}`)
			}
			const mergeAndDeduplicate = (list1, list2, key) => {
				return [...new Map([...list1, ...list2].map(item => [item[key], item])).values()];
			}
			if (this.type == 'source') {
				this.sourceList = result
			} else if (this.type == 'user') {
				this.userList = mergeAndDeduplicate(this.userList, result, 'user_name')
			} else {
				this.targetList = mergeAndDeduplicate(this.targetList, result, 'user_name')
			}
			this.showPopup = false
		},
		/**
		 * 根据素材群id，获取群成员列表
		 */
		getUserList () {
			let item = this.sourceList[0]
			return new Promise((resolve, reject) => {
				this.$api.getUserByGroupId({
					username: item.user_name,
					owner: item.owner
				}, true).then(res => {
					let list = res.data.list || []
					// list = list.map(item => this.camelToSnake(item))
					// this.list = this.markChecked(list, this.userList) // 处理回显
					this.list = list
					this.originUserList = list // 过滤时用
					resolve()
				})
			})
		},
		handleQuestion () {
			this.$toast('为什么没有我的群')
		},
		// 底部加载更多
		onLoad () {
			if (this.type !== 'user') {
				this.getGroupList()
			}
		},
		/**
		 * 
		 * @param {普通群/用户列表} list 
		 * @param {选中数据列表} dataList 
		 */
		markChecked (list, dataList) {
			const usernames = new Set(dataList.map(item => item.user_name))
			return list.map(item => ({
				...item,
				checked: usernames.has(item.user_name) // 判断 id 是否存在
			}));
		},
		// 检测是否有相同数据
		checkSimilar (sourceList, targetList) {
			let sourceIds = new Set(sourceList.map(item => item.user_name))
			const hasSameId = targetList.some(item => sourceIds.has(item.user_name))
			if (hasSameId) {
				return true
			}
			return false
		},
		// 驼峰转下划线
		camelToSnake (obj) {
			const result = {};
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
				// 将驼峰转换为下划线
				const snakeKey = key.replace(/([A-Z])/g, "_$1").toLowerCase()
				result[snakeKey] = obj[key]
				}
			}
			return result
		},
		showNotify () {
			Notify({
				type: 'success',
				message: '保存成功，需手动启用后才可正常发单',
				duration: '1200'
			})
			this.$common.setHeader({
				str_link_color: '#07c160',
				end_link_color: '#07c160'
			})
			setTimeout(() => {
				this.$router.go(-1)
			}, 1200)
		}
 	}
}
</script>
<style lang="less" scoped>
.cont {
	font-size: 14px;
	padding-top: 46px;
	.sync-text {
		line-height: 1.3;
	}
	.sync-btn {
		padding: 5px;
		color: #ffffff;
		background: #f5f5f5;
		border-radius: 20px;
	}
	.footer {
        position: fixed;
        bottom: 20px;
        left: 10px;
        right: 10px;
        z-index: 10;
    }
	.item {
		padding: 10px 0;
		&-title {
			.sort {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 14px;
				height: 14px;
				margin-right: 5px;
				background: #000000;
				color: #ffffff;
				border-radius: 2px;
			}
		}
		&-content {
			padding: 10px;
			background: #eeeeee;
		}
		&-grid {
			display: grid;
			padding: 10px 0;
			grid-template-columns: repeat(5, 20%);
			grid-gap: 5px 0;
			background: #ffffff;
			border-radius: 4px;
			.grid-box {
				position: relative;
				padding: 5px;
				.close {
					position: absolute;
					top: 0;
					right: 0;
				}
				
				.group-img {
					width: 48px;
					height: 48px;
					margin: 0 auto 5px;
					border-radius: 4px;
					overflow: hidden;
					border: 1px dashed transparent;
					&.group-btn {
						border: 1px dashed #b2b2b2;
					}
					.img {
						width: 100%;
					}
				}
				
			}
		}
	}
}
.popup-content {
	padding: 10px 0;
	background: #f5f5f5;
	.popup-title {
		position: relative;
		&:after {
			content: '';
			position: absolute;
			width: 16px;
			height: 16px;
			bottom: -2px;
			right: -6px;
			background: rgba(137,153,241,.3);
			border-radius: 50%;
		}
	}
	::v-deep .search {
		.van-search {
			padding-top: 5px;
		}
		.van-search__content {
			background: #ffffff;
		}
	}
}
.list {
	height: 300px;
	padding: 0 10px;
	margin-bottom: 10px;
    overflow-y: auto;
	&-item {
		position: relative;
		padding: 5px 10px;
		padding-right: 40px;
		background: #ffffff;
		border-radius: 8px;
		.item-img {
			width: 36px;
			height: 36px;
		}
		.check {
			position: absolute;
			top: 50%;
			right: 10px;
			transform: translateY(-50%);
		}
	}
}
</style>